/**
 * Created by kevin on 2017/7/3.
 */
var model= require('./model');
var Package = require('./Packages');

var Guanjia = model.createModel({
    key : {type : String,default:"uniqe"},
    name: String,
    desc : String,
    android : {type:model.objId,ref:'Applications'},
    ios : {type:model.objId,ref:'Applications'},
    ctime : {type : Date,default:Date.now}
},'Guanjia');


Guanjia.config = function (doc,callback) {
    Guanjia.count({key : "uniqe"},function (err,count) {
        if (!count || count === 0) {
            Guanjia.create(doc,callback);
        } else  {
            Guanjia.findOneAndUpdate({key : "uniqe"},doc,callback);
        }
    });
};

Guanjia.getInfo = function (callback) {
    Guanjia.findOne({key:"uniqe"},null,{lean:true}).populate("android").populate("ios").exec(function (err,guanjia) {
        if (err || !guanjia) {
            if (callback) {
                callback(err,null);
            }
        } else  {
            var android = guanjia.android;
            var ios = guanjia.ios;
            if (android) {
                Package.getPartByAppId(android._id,1,1,function (err,list) {
                    if (list && list.length > 0) {
                        guanjia.androidPackage = list[0];
                    } else  {
                        guanjia.androidPackage = null;
                    }
                    if (ios) {
                        Package.getPartByAppId(ios._id,1,1,function (err,list) {
                            if (list && list.length > 0) {
                                guanjia.iosPackage = list[0];
                            } else  {
                                guanjia.iosPackage = null;
                            }
                            if (callback) {
                                callback(null,guanjia);
                            }
                        });
                    } else  {
                        if (callback) {
                            callback(null,guanjia);
                        }
                    }

                });
            } else  {
                if (ios) {
                    Package.getPartByAppId(ios._id,1,1,function (err,list) {
                        if (list && list.length > 0) {
                            guanjia.iosPackage = list[0];
                        } else  {
                            guanjia.iosPackage = null;
                        }
                        if (callback) {
                            callback(null,guanjia);
                        }
                    });
                } else  {
                    if (callback) {
                        callback(null,guanjia);
                    }
                }
            }

        }
    });
};

module.exports = Guanjia;